<?php /**
 * 模板编译类
 */
class CompileClass
{
    private $template;                        /*待编译文件*/
    private $content;                        /*需要替换的文件内容*/
    private $comfile;                        /*编译后文件*/
    private $left = '{';                    /*左界定符*/
    private $right = '}';                    /*右界定符*/
    private $value = array();                /*值栈*/
    private $config;                       //配置
    private $T_P = array();
    private $T_R = array();

    /*
     * @param $template需要编译的模板文件
     * @param $compilefile 编译之后的文件
     */
    public function __construct($template, $compilefile, $config)
    {
        $this->config=$config;
        $this->template = $template;
        $this->comfile = $compilefile;
        $this->content = file_get_contents($template);

        if ($this->config['phpturn'] === false) {
            $this->T_P = "/<\? (=|php |)(.+?)\?>/is";
            $this->T_R = "&lt;? \\1\\2? &gt;";
        }

        $this->T_P[] = "#\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}#";  //变量
        $this->T_P[] = "#\{(loop|foreach) \\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)}#i";
        $this->T_P[] = "#\{\/(loop|foreach|if)}#i";
        $this->T_P[] = "#\{([K|V])\}#";
        $this->T_P[] = "#\{if (.*?)\}#i";
        $this->T_P[] = "#\{(else if|elseif)(.*?)\}#i";
        $this->T_P[] = "#\{else\}#i";
        $this->T_P[] = "#\{(\#|\*)(.*?)(\#|\*)\}#";  //注释
        $this->T_P[] = "#\{([K|V].*)\}#";  //解决输出对象的问题

        $this->T_R[] = "<?php echo \$this->value['\\1'];?>";
        $this->T_R[] = "<?php foreach ((array)\$this->value['\\2'] as \$K => \$V ) { ?>";
        $this->T_R[] = "<?php } ?>";
        $this->T_R[] = "<?php echo \$\\1; ?>";
        $this->T_R[] = "<?php if(\\1) { ?>";
        $this->T_R[] = "<?php }else if(\\2) { ?>";
        $this->T_R[] = "<?php }else{ ?>";
        $this->T_R[] = "";
        $this->T_R[] = "<?php echo \$\\1; ?>";
    }

    public function compile()
    {
        $this->c_var2();
        $this->c_staticFile();
        file_put_contents($this->comfile, $this->content);
    }

    private function c_var2()
    {
        $this->content = preg_replace($this->T_P, $this->T_R, $this->content);
    }

    private function c_staticFile()
    {
        if($this->config['jsturn']){
            $this->content = preg_replace('/\{\!(.*?)\!\}/', '<script scr=\\1'.'?t='.time().'></script>', $this->content);
        }
    }

    public function __set($key,$value){
        $this->$key=$value;
    }

    public function __get($key){
        return $this->$key;
    }
}

?>